function makeCode(canvas: HTMLCanvasElement, codeLength: number = 4) {
  const valueArr = [];
  const canvasWidth = canvas.width;
  const canvasHeight = canvas.height;
  const context = canvas.getContext('2d')!;
  context.clearRect(0, 0, canvasWidth, canvasHeight);
  //设置所有可能出现的字符
  const codeLib = [
    'A',
    'B',
    'C',
    'E',
    'F',
    'G',
    'H',
    'K',
    'L',
    'M',
    'N',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'W',
    'X',
    'Y',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'h',
    'k',
    'm',
    'n',
    'p',
    'r',
    's',
    't',
    'w',
    'x',
    'y',
    'z',
    '3',
    '4',
    '5',
    '6',
    '8',
  ];
  const codeLibLength = codeLib.length;
  for (let i = 0; i < codeLength; i++) {
    // 获得随机字符
    const txt = codeLib[Math.floor(Math.random() * codeLibLength)];
    valueArr.push(txt.toLowerCase());
    //产生-20~20之间的随机弧度
    const deg = ((Math.random() * 40 - 20) * Math.PI) / 180;
    //文字在canvas上的坐标位置
    const x = (canvasWidth / (codeLength + 1)) * (i + 0.5);
    const y = Math.random() * ((canvasHeight * 1) / 5) + (canvasHeight * 7) / 10;
    //字体设置
    const fontSize = (canvasHeight * 3) / 4;
    context.font = 'bold ' + fontSize + 'px 微软雅黑';
    context.translate(x, y);
    context.rotate(deg);
    context.fillStyle =
      'rgb(' +
      Math.ceil(Math.random() * 200) +
      ',' +
      Math.ceil(Math.random() * 200) +
      ',' +
      Math.ceil(Math.random() * 200) +
      ')';
    context.fillText(txt, 0, 0);
    context.rotate(-deg);
    context.translate(-x, -y);
  }
  //验证码上显示线条
  for (let i = 0; i < 5; i++) {
    context.strokeStyle =
      'rgb(' +
      Math.ceil(Math.random() * 100 + 155) +
      ',' +
      Math.ceil(Math.random() * 100 + 155) +
      ',' +
      Math.ceil(Math.random() * 100 + 155) +
      ')';
    context.beginPath();
    context.moveTo(Math.random() * canvasWidth, Math.random() * canvasHeight);
    context.lineTo(Math.random() * canvasWidth, Math.random() * canvasHeight);
    context.stroke();
  }
  //验证码上显示小点
  for (let i = 0; i <= 24; i++) {
    context.strokeStyle =
      'rgb(' +
      Math.ceil(Math.random() * 100 + 155) +
      ',' +
      Math.ceil(Math.random() * 100 + 155) +
      ',' +
      Math.ceil(Math.random() * 100 + 155) +
      ')';
    context.beginPath();
    const x = Math.random() * canvasWidth;
    const y = Math.random() * canvasHeight;
    context.moveTo(x, y);
    context.lineTo(x + 1, y + 1);
    context.stroke();
  }
  //返回当前验证码的值
  return valueArr.join('');
}

export default makeCode
